<?php
namespace app\modules\backend\controllers;

use Yii;
use yii\web\Controller;
use app\models\Admin;
use app\models\search\AdminSearch;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\rbac\Item;
use app\models\search\AuthItemSearch;
use app\models\Config;
/**
 * PersonalController implements the CRUD actions for Admin model.
 */
class PersonalController extends Controller
{

    public $type = Item::TYPE_ROLE;
    public $layout = 'admin'; //设置全局模板为后台模板
    public $adminId;
    public $adminName;

    /**
     * 初始化配置信息
     * 网站配置或模板配置等
     */
    public function init() {
        parent::init();
        Yii::$app->params['basic'] = Config::getConfigs('basic');
        //登录用户的信息
        $session = \Yii::$app->session;
        $this->adminId = $session->get('id');
        $this->adminName = $session->get('username');
        return true;
    }

    /**
     * 修改个人信息
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionProfile()
    {
    	$id = $this->adminId;
    	$id = 1;
    	
        $model = Admin::findOne($id);
        $model->scenario = 'update';
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index/index']);
        } else {
            return $this->render('profile', [
                'model' => $model,
            ]);
        }
    }
    /**
     * 修改登录密码
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionModifypwd()
    {
    	$id = $this->adminId;
    	$id = 1;
    	
        $model = Admin::findOne($id);
        $model->scenario = 'update';
        
        if (Yii::$app->request->isPost) {
        	$admin = new Admin();
        	$oldPwd = Yii::$app->request->post('oldPwd');
        	$newPwd = Yii::$app->request->post('newPwd');
        	$confirmPwd = Yii::$app->request->post('confirmPwd');
        	
        	if($model->validatePassword($oldPwd)){
                
        		if($newPwd == $confirmPwd){
        			$model->password = $model->setPassword($newPwd);
        			$model->save();
                    Yii::$app->session->setFlash("success","更新成功!");
                    //$this->message("success","更新成功","index/index");
        			return $this->redirect(['index/index']);
        		}else{
        			Yii::$app->session->setFlash('error', '两次密码不一致');
        		}
        	}else{
        		Yii::$app->session->setFlash('error', '旧密码错误');
        	}
            
        } 
        return $this->render('modifypwd', [
                'model' => $model,
            ]);
        
    }
}
